﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using NCrawler.Extensions;

namespace ZCrawler
{
    public class ZRuleRange : ZBasicRule
    {
        public ZRuleRange() { }
        public ZRuleRange(string sTag,string eTag,string fn) : base(fn) 
        {
            tag = 0;
            startTag = sTag;
            endTag = eTag;
        }
        public override string Process(HtmlDocument doc)
        {
            if (EOF) return "";
            string html = doc.DocumentNode.OuterHtml;
            int startIndex = html.IndexOf(startTag, tag) + startTag.Length;
            EOF = startIndex - startTag.Length == -1;
            if (!EOF)
            {
                int endIndex = html.IndexOf(endTag, startIndex);
                string result = html.Substring(startIndex, endIndex - startIndex);
                processors.ForEach(p =>
                    {
                        result = p.Process(result);
                    });
                tag = endIndex + endTag.Length;
                EOF = html.IndexOf(startTag, tag) == -1;
                return result.Trim();
            }
            return "";
        }
        public override string Description()
        {
            return "<Rule><start>{0}</start><end>{1}</end></Rule>".FormatWith(startTag, endTag);
        }
    }
}
